<?php
session_start();
if(($_SESSION['datos_admin']['estado'] == "autenticado") && ($_SESSION['datos_admin']['tipo'] == 3)) {
$idempresa = $_SESSION['datos_admin']['user'];


include("header.php");

$mydirname = basename( dirname( __FILE__ ) ) ;
	
require_once( XOOPS_ROOT_PATH."/modules/$mydirname/include/gtickets.php" ) ;

$myts =& MyTextSanitizer::getInstance();
$module_id = $xoopsModule->getVar('mid');

/* if (is_object($xoopsUser)) {
    $groups = $xoopsUser->getGroups();
} else {
	$groups = XOOPS_GROUP_ANONYMOUS;
}

$gperm_handler =& xoops_gethandler('groupperm');

if (isset($_POST['item_id'])) {
    $perm_itemid = intval($_POST['item_id']);
} else {
    $perm_itemid = 0;
}
//If no access
if (!$gperm_handler->checkRight("jobs_submit", $perm_itemid, $groups, $module_id)) {
    redirect_header(XOOPS_URL."/user.php", 3, _NOPERM);
    exit();
} */


/**
 * Funci�n para ingresar los datos en el formulario de ofertas
 *
 * @param int $cid: n�mero que identifica el programa elegido a trav�s de una relaci�n con la tabla jobs_categories
 */
function addindex($cid)
{
    //global $xoopsDB, $xoopsConfig, $xoopsUser, $xoopsTheme, $photomax, $xoopsLogger;
    global $xoopsDB, $xoopsConfig, $xoopsUser, $xoopsTheme, $xoopsLogger, $xoopsModule, $xoopsModuleConfig, $mydirname, $idempresa;

	$token = $GLOBALS['xoopsSecurity']->createToken();
	include_once (XOOPS_ROOT_PATH."/modules/$mydirname/include/functions.php");

	$wysiwyg_folder = XOOPS_ROOT_PATH."/class/wysiwyg";
	
	if ( file_exists( $wysiwyg_folder ) && ($xoopsModuleConfig['koivi'] == '1')) {
	include_once XOOPS_ROOT_PATH."/class/xoopsformloader.php";
	include_once XOOPS_ROOT_PATH . "/class/wysiwyg/formwysiwygtextarea.php"; 
	}else{
	include_once (XOOPS_ROOT_PATH."/include/xoopscodes.php");
	}
	include_once (XOOPS_ROOT_PATH."/class/xoopstree.php");
	$mytree = new XoopsTree($xoopsDB->prefix("jobs_categories"),"cid","pid");

	//if ($cid =="") {
	//	redirect_header("index.php",1,_JOBS_ADDLISTING);
	//	exit();
	//}	
		$jobsdays=$xoopsModuleConfig['jobsdays'];
		
		$login_empresa = $_SESSION['datos_admin']['user'];
		$submitter = $login_empresa;
		
        /* $result = $xoopsDB->query("select cid FROM ".$xoopsDB->prefix("jobs_empresas")." WHERE login='{$login_empresa}'");
        list($submitter) = $xoopsDB->fetchRow($result); */

        $sal = $xoopsDB->query("select nom_price from ".$xoopsDB->prefix("jobs_price")."");
	    list($nom_price) = $xoopsDB->fetchRow($sal);

//Detecci�n de errores
		echo "<script type=\"text/javascript\">

function validarEmail(valor) {
 re=/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/
    if(!re.exec(valor))    {
//        return false;
        return true;
    }else{
        return true;
    }
}


          function verify() {
		  var a = document.add.email.value;
          var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+.[A-Za-z0-9_.]+[A-za-z]$/;
		  
		  var precio = document.add.price.value;
		  var price1 = {$nom_price};
                var msg = \""._VALIDAR_OFERTAS."\\n__________________________________________________\\n\\n\";
                var errors = \"FALSE\";

                if (precio < price1) {
                        errors = \"TRUE\";
                        msg += \""._VALIDPRICE."\\n\";
                }
                if (document.add.title.value == \"\") {
                        errors = \"TRUE\";
                        msg += \""._VALIDCARGOSOL."\\n\";
                }
                 if (document.add.exprequerida.value == \"\") {
                        errors = \"TRUE\";
                        msg += \""._VALIDEXP2."\\n\";
                }
				 if (document.add.expire.value == \"0\") {
                        errors = \"TRUE\";
                        msg += \""._VALIDTIEMPO."\\n\";
                }
				if (document.add.town.value == \"\") {
                        errors = \"TRUE\";
                        msg += \""._VALIDSEDE."\\n\";
                }
				if (document.add.contactinfo.value == \"\") {
                        errors = \"TRUE\";
                        msg += \""._VALIDCONTACTO."\\n\";
                }				
				if (document.add.desctext.value == \"\") {
                        errors = \"TRUE\";
                        msg += \""._VALIDFUNCIONES."\\n\";
                }				
				if (document.add.requirements.value == \"\") {
                        errors = \"TRUE\";
                        msg += \""._VALIDCOMPETENCIAS."\\n\";
                }							
				
	//			if (a.length != 0) {     
        //          if (!validarEmail(a)) {
	//		           errors = \"TRUE\";
        //               msg += \""._EMAIL_ERROR."\\n\";
	//		     }
			 }    
												
                if (errors == \"TRUE\") {
                        msg += \"__________________________________________________\\n\\n"._VALIDAR_OFERTAS2."\\n\";
						alert(msg);			
                        return false;
                }
		  }
 </script>";
		
		/**
		 * Funci�n para ingresar solo n�meros en un campo de texto
		 */
   echo "<script type=\"text/javascript\">
	 function numeros(e) {
    tecla = (document.all) ? e.keyCode : e.which; 
    if (tecla==8) return true; 
    patron =/\d/; 
    te = String.fromCharCode(tecla); 
    return patron.test(te);
    } 
      </script>"; 
		
		list($numrows) = $xoopsDB->fetchRow($xoopsDB->query("select cid, title, affprice from ".$xoopsDB->prefix("jobs_categories").""));
    
		if ($numrows>0) {
			echo "<table width='100%' border='0' cellspacing='1' cellpadding='8'><tr class='bg4'><td valign='top'>\n";
		
			if ($xoopsModuleConfig['moderated'] == '1') {
			    echo "<b>"._JOBS_ADDLISTING3."</b><br /><br /><center>"._JOBS_JOBMODERATE."$jobsdays"._JOBS_MODERATE2."
				</center><br /><br />";
			} else {
				echo "<b><center>"._JOBS_ADDLISTING3."</b><br /><br />"._JOBS_JOBNOMODERATE."</center><br />";
			}
			
	   $nom_price = number_format($nom_price,0,",",".");	
       echo "<center>"._SALARIO_MINIMO."<b>$nom_price. </b>"._SALARIO_MINIMO2. _VINCULO ."<br><br>"._REQUERIDO.  "</center>";

			echo "<form method=\"post\" action=\"addlisting.php\" enctype=\"multipart/form-data\" name=\"add\" onsubmit=\"return verify();\">";
			echo "<table width='100%' class='outer' cellspacing='1'>";		
			
			$sec = $xoopsDB->query("select sector FROM ".$xoopsDB->prefix("jobs_empresas")." WHERE login=$idempresa");
	    list($sector) = $xoopsDB->fetchRow($sec);
			
			echo "<tr><td width='35%' class='even'><b>"._MOSTRAR_NOMBRE."<b> </td><td class='even'>
				<input type=\"radio\" name=\"mostrar\" value=\"si\" checked>"._SNOMBRE."<br>
				<input type=\"radio\" name=\"mostrar\" value=\"no\" />"._NNOMBRE."
				<!--<input type=\"text\" name=\"company\" size=\"50\" maxlength=\"50\" disabled=\"disabled\"/> -->
</td></tr>";

?>
			<tr>
			 <td class='even'></td>
			 <td><input type="hidden" name="company" id="company" value="<?= $sector ?>">
			        
			    
			 </td>
			</tr>
			<?			
	//echo "<tr><td width='35%' class='even'><b><i>"._JOBS_COMPANY2."</i></b> </td><td class='even'><input type=\"text\" name=\"company\" size=\"50\" maxlength=\"50\" disabled=\"disabled\"/></td></tr>";

$module_id = $xoopsModule->getVar('mid');

if (is_object($xoopsUser)) {
    $groups = $xoopsUser->getGroups();
} else {
	$groups = XOOPS_GROUP_ANONYMOUS;
}

$gperm_handler =& xoops_gethandler('groupperm');

if (isset($_POST['item_id'])) {
    $perm_itemid = intval($_POST['item_id']);
} else {
    $perm_itemid = 0;
}

//If no access
/* if (!$gperm_handler->checkRight("jobs_premium", $perm_itemid, $groups, $module_id)) {
		
    echo "<tr>
				<td width='30%' class='even'>"._JOBS_HOW_LONG." </td><td class='even'>$jobsdays  "._JOBS_DAY."</td>
				</tr><input type=\"hidden\" name=\"expire\" value=\"$jobsdays\" />";
		}else{
				echo "<tr>
				<td width='30%' class='odd'>"._JOBS_HOW_LONG." </td><td class='odd'><input type=\"text\" name=\"expire\" size=\"3\" maxlength=\"3\" value=\"$jobsdays\"/>  "._JOBS_DAY."</td>
				</tr>";
		} */
           echo "<tr>
		   <td width='35%' class='odd'><b>"._JOBS_HOW_LONG._AST."</b> </td><td class='odd'><input type=\"text\" name=\"expire\" size=\"3\" maxlength=\"3\" value=\"$jobsdays\" onKeypress=\"return numeros(event);\" />  "._JOBS_DAY."</td>
		   </tr>";

           if (!isset($jobsnumvac)) $jobsnumvac = 1;
           echo "<tr>
		   <td width='35%' class='odd'><b>N&uacute;mero de vacantes para esta solicitud</b> </td><td class='odd'><input type=\"text\" name=\"numvacantes\" size=\"3\" maxlength=\"3\" value=\"$jobsnumvac\" onKeypress=\"return numeros(event);\" /> </td>
		   </tr>";
           echo "<tr><td width='35%' class='even'><b>"._PERFIL_CANDIDATO._AST."</b> </td><td class='even'>";
		   $mytree->makeMySelBox("title", "title", $cid); 
			echo "</td></tr>";
									
				echo "<tr>
				<td width='35%' class='odd'><b>"._PROGRAMA2."</b> </td><td class='odd'><input type=\"text\" name=\"programa\" size=\"50\" maxlength=\"100\" /></td>
				</tr>";
				echo "<tr>
				<td width='35%' class='even'><b>"._CARGODE._AST."</b> </td><td class='even'><input type=\"text\" name=\"title\" size=\"50\" maxlength=\"100\" /></td>
				</tr><tr>
				<td width='35%' class='odd'><b>"._EXPERIENCIA._AST."</b> </td><td class='odd'>
				<select name=\"exprequerida\"><option selected></option>";
				
				$exprequeridalist = array(_EXP0, _EXP1, _EXP2, _EXP3, _EXP4, _EXP5, _EXP6,);
				
				foreach ($exprequeridalist as $value){
				    echo "<option value=\"{$value}\">{$value}</option>";
				}
				
				echo "</select></td>
				</tr><tr>
				<td width='35%' class='even'><b>"._TIPOCONTRATO."</b> </td><td class='even'><input type=\"text\" name=\"tipocontrato\" size=\"30\" maxlength=\"30\" /></td>
				</tr><tr>
				<td width='35%' class='odd'><b>"._JOBS_DESC._AST."</b> <br /></td><td class='odd'>";
//Editor koivi
			$desctext = "";
		$wysiwyg_folder = XOOPS_ROOT_PATH."/class/wysiwyg";
	if ( file_exists( $wysiwyg_folder ) && ($xoopsModuleConfig['koivi'] == '1')) {
			$wysiwyg_text_area= new XoopsFormWysiwygTextArea( _JOBS_DESC2, desctext, $desctext, '100%', '200px','small');
	echo $wysiwyg_text_area->render();
			} else {
			ob_start();
			$GLOBALS["desctext"] = $desctext;
			xoopsCodeTarea("desctext",30,6);
			$xoops_codes_tarea = ob_get_contents();
			ob_end_clean();
			echo $xoops_codes_tarea;
			}
//			
		      echo "</td></tr><tr>
		      <td width='35%' class='even'><b>"._JOBS_REQUIRE._AST."</b><br /></td><td class='even'>";
//Editor koivi		      
			$requirements = "";
		$wysiwyg_folder = XOOPS_ROOT_PATH."/class/wysiwyg";
	if ( file_exists( $wysiwyg_folder ) && ($xoopsModuleConfig['koivi'] == '1')) {
			$wysiwyg_requirements_area= new XoopsFormWysiwygTextArea( _JOBS_REQUIRE, requirements, $requirements, '100%', '200px','small');
	echo $wysiwyg_requirements_area->render();
			} else {
			//$requirements ="";
			ob_start();
			$GLOBALS["requirements"] = $requirements;
			xoopsCodeTarea("requirements",30,6);
			$xoops_codes_tarea = ob_get_contents();
			ob_end_clean();
			echo $xoops_codes_tarea; 
			}
//			
			echo "</td></tr>";
								
			echo "<tr>
			<td width='35%' class='odd'><b>"._JOBS_PRICE2._AST."</b></td><td class='odd'>".$xoopsModuleConfig['monnaie']."<input type=\"text\" name=\"price\" size=\"30\" maxlength=\"12\" onKeypress=\"return numeros(event);\"/>
			</td></tr>";
					
				echo "<tr>
				<td width='35%' class='even'><b>"._JOBS_CONTACTINFO._AST."</b></td><td class='even'><textarea name=\"contactinfo\" cols=\"28\" rows=\"4\"></textarea></td>
				</tr><tr>
				<td width='35%' class='odd'><b>"._JOBS_EMAIL."</b> </td><td class='odd'><input type=\"text\" name=\"email\" size=\"50\" maxlength=\"50\" /></td>
				</tr>";
					
				if($xoopsUser) {
				$iddd =$xoopsUser->getVar("uid", "E");
				$idd =$xoopsUser->getVar("name", "E");// Real name
				$idde =$xoopsUser->getVar("email", "E");
				$iddn =$xoopsUser->getVar("uname", "E");// user name
			}
	
			$time = time();

			/* if ($idd) {
				echo "</tr><tr>
					<td width='30%' class='outer'>"._JOBS_SURNAME." </td><td class='odd'><input type=\"text\" name=\"submitter\" size=\"30\" value=\"$idd\" /></td>";
			}else{
				echo "</tr><tr>
					<td width='30%' class='outer'>"._JOBS_SURNAME." </td><td class='odd'><input type=\"text\" name=\"submitter\" size=\"30\" value=\"$iddn\" /></td>";
			} */
				echo "<tr>
				<td width='35%' class='even'><b>"._JOBS_TOWN._AST."</b></td><td class='even'><input type=\"text\" name=\"town\" size=\"50\" maxlength=\"50\"/></td>
				</tr><tr>
				<td width='35%' class='odd'><b>"._NOTA."</b></td><td class='odd'><textarea name=\"nota\" cols=\"28\" rows=\"4\"></textarea></td>
				</tr>
				</table><br /><br>";
				
				echo "<center>"._AVISO_OFERTAS."</center><br>";
				echo "<input type=\"hidden\" name=\"submitter\" value=\"$submitter\" />
				<input type=\"hidden\" name=\"usid\" value=\"$iddd\" />
				<input type=\"hidden\" name=\"op\" value=\"AddListingsOk\" />";
				echo "<input type=\"hidden\" name=\"token\" value=\"$token\" />";
				if ($xoopsModuleConfig['moderated'] == '1') {
		    	echo "<input type=\"hidden\" name=\"valid\" value=\"No\" />";
			} else {
				echo "<input type=\"hidden\" name=\"valid\" value=\"Yes\" />";
			}
			echo "<input type=\"hidden\" name=\"lid\" value=\"0\" />
				<input type=\"hidden\" name=\"date\" value=\"$time\" />
				<table width='100%' class='outer' cellspacing='1'><tr>
			    <td colspan=2><br><center><input type=\"submit\" value=\""._PUBLICAR."\" />
				<input name=\"btncancelar\" type=\"button\" id=\"btncancelar\" onClick=\"self.location.href='principalempresas.php'\"  value=\""._CANCELAR."\"></center>
				</td></tr></table>";
			echo "</form>";
			echo "</td></tr></table>";
	   	}
	}


/**
 * Funci�n para insertar los datos del formulario en la tabla 'jobs_listing'
 *
 * @param int $lid
 * @param int $cat
 * @param string $title
 * @param string $tipocontrato
 * @param string $exprequerida
 * @param string $programa
 * @param string $nota
 * @param int $expire
 * @param unknown_type $type
 * @param string $company
 * @param string $desctext
 * @param string $requirements
 * @param string $tel
 * @param int $price
 * @param string $typeprice
 * @param string $contactinfo
 * @param string $date
 * @param string $email
 * @param string $submitter
 * @param unknown_type $usid
 * @param string $town
 * @param string $valid
 * @param unknown_type $_FILES
 */
function AddListingsOk($lid, $cat, $title, $tipocontrato, $exprequerida, $programa, $nota, $expire, $type, $company, $mostrar, $desctext, $requirements, $tel, $price, $typeprice, $contactinfo, $date, $email, $submitter, $usid, $town, $valid, $_FILES, $sector, $numvacantes)
{
	global $xoopsDB, $xoopsConfig, $xoopsModule, $xoopsModuleConfig, $destination, $myts, $xoopsLogger, $mydirname;

	if (!$GLOBALS['xoopsSecurity']->check(true, $_REQUEST['token'])) {
	redirect_header(XOOPS_URL."/modules/$mydirname/principalempresas.php", 3, implode('<br />', $GLOBALS['xoopsSecurity']->getErrors()));
		}
	
	include(XOOPS_ROOT_PATH."/modules/$mydirname/include/functions.php");


	$title = $myts->makeTboxData4Save($title);
	$tipocontrato = $myts->makeTboxData4Save($tipocontrato);
	$exprequerida = $myts->makeTboxData4Save($exprequerida);
	$programa = $myts->makeTboxData4Save($programa);
	$nota = $myts->makeTboxData4Save($nota);
	$expire = $myts->makeTboxData4Save($expire);
	$type = $myts->makeTboxData4Save($type);
	$company = $myts->makeTboxData4Save($company);
	$desctext = $myts->makeTboxData4Save($desctext);
	$requirements = $myts->makeTboxData4Save($requirements);
	$tel = $myts->makeTboxData4Save($tel);
	$price = $myts->makeTboxData4Save($price);
	$typeprice = $myts->makeTboxData4Save($typeprice);
	$contactinfo = $myts->makeTboxData4Save($contactinfo);
	$submitter = $myts->makeTboxData4Save($submitter);	
	$town = $myts->makeTboxData4Save($town);
	
	
	$filename = '';
	
	 if ($mostrar == 'si'){
	    $idempresa = $_SESSION['datos_admin']['user'];
	    list($company) = $xoopsDB->fetchRow($xoopsDB->query("select empresa FROM ".$xoopsDB->prefix("jobs_empresas")." WHERE login=$idempresa"));    	 	
	}
		
	$xoopsDB->query("INSERT INTO ".$xoopsDB->prefix("jobs_listing")." values ('', '$cat', '$title', '$tipocontrato', '$exprequerida', '$programa', '$nota', '$expire', '$type', '$company', '$desctext', '$requirements', '$tel', '$price', '$typeprice', '$contactinfo', '$date', '$email', '$submitter', '$usid',  '$town',  '$valid', '$filename', '0', '$sector', '$numvacantes')");

	$sql = "INSERT INTO ".$xoopsDB->prefix("jobs_listing")." values ('', '$cat', '$title', '$tipocontrato', '$exprequerida', '$programa', '$nota', '$expire', '$type', '$company', '$desctext', '$requirements', '$tel', '$price', '$typeprice', '$contactinfo', '$date', '$email', '$submitter', '$usid',  '$town',  '$valid', '$filename', '0', '$sector')";


        $fw = fopen('testsql', 'w');
        fwrite($fw, $sql);
        fclose($fw);

	if($valid == 'Yes'){

	$notification_handler =& xoops_gethandler('notification');
	$lid = $xoopsDB->getInsertId();
	$tags=array();
	$tags['TITLE'] = $title;
	$tags['TYPE'] = $type;
	$tags['LINK_URL'] = XOOPS_URL . '/modules/'.$mydirname.'/index.php?pa=viewlistings'. '&lid=' . $lid;
	$sql = "SELECT title FROM " . $xoopsDB->prefix("jobs_categories") . " WHERE cid=" . $cat;
	$result = $xoopsDB->query($sql);
	$row = $xoopsDB->fetchArray($result);
	$tags['CATEGORY_TITLE'] = $row['title'];
	$tags['CATEGORY_URL'] = XOOPS_URL . '/modules/'.$mydirname.'/index.php?pa=jobsview&cid="' . $cat;
	$notification_handler =& xoops_gethandler('notification');
	$notification_handler->triggerEvent('global', 0, 'new_listing', $tags);
	$notification_handler->triggerEvent('category', $cid, 'new_listing', $tags);
	$notification_handler->triggerEvent ('listing', $lid, 'new_listing', $tags );

$cabeceras = 'Content-type: text/html'. "\r\n" ;

$body= "Una empresa ha ingresado una nueva solicitud de hoja de vida. <br>
Requerimientos: {$requirements} \n
Telefono: {$tel} \n
Precio: {$price} \n
Contacto: {$email}
";

mail("darcila@funlam.edu.co", "Nueva solicitud", $body, $cabeceras);



	}


	redirect_header("principalempresas.php",3,_JOBS_JOBADDED);
	exit();
	}
	

#######################################################
foreach ($_POST as $k => $v) {
	${$k} = $v;
}

if(!isset($_POST['cid']) && isset($_GET['cid']) ) {
	$cid = $_GET['cid'] ;
}

if(!isset($_POST['op']) && isset($_GET['op']) ) {
	$op = $_GET['op'] ;
}

if (!isset($op)) {
	$op = '';
}

switch($op) {	
	case "AddListingsOk":
   	AddListingsOk($lid, $cid, $title, $tipocontrato, $exprequerida, $programa, $nota, $expire, $type, $company, $mostrar, $desctext, $requirements, $tel, $price, $typeprice, $contactinfo, $date, $email, $submitter, $usid, $town, $valid, $_FILES, $sector, $numvacantes);
   	break;

	default:
	include(XOOPS_ROOT_PATH."/header.php");
	addindex($cid);
	
	echo "<br /><br />
<div align=\"center\">" . _INFO_PAG . "</div>
<br /><br />";
	
	
	include(XOOPS_ROOT_PATH."/footer.php");
	break;
}
}else
{
// Usuario que no se ha logueado
echo "No tienes permiso para entrar a esta pagina";
exit();
} 
?>
